<template>
    <el-dialog
  :title="title"
  :visible.sync="visible"
  width="40%"
  :before-close="handleClose">
    <el-form :model="formData" :rules="rules" ref="formData" label-width="100px" class="demo-ruleForm" style="width:90%">
    <el-form-item label="标签名称：" prop="name">
        <el-input v-model="formData.name"></el-input>
    </el-form-item>
    <el-form-item label="分类名称：" prop="categoryId">
        <el-select v-model="formData.categoryId" clearable filterable>
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            
        </el-select>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" size="mini" @click="submitForm('formData')">确定</el-button>
        <el-button @click="handleClose" size="mini">取消</el-button>
    </el-form-item>
    </el-form>
    </el-dialog>
</template>

<script>
import api from '@/api/label'
export default {
    data() {
        return {
            rules: {
                name: [
                    { required: true, message: '请输入标签名称', trigger: 'blur' }
                    
                ],
                categoryId: [
                    { required: true, message: '请输入分类名称', trigger: 'change' },                   
                ],
                
            }
        }
    },
    props:{
        visible:{
            type:Boolean,
            default:false
        },
        title:{
            type:String,
            default:''
        },
        formData:{
            type:Object,
            default:{}
        },
        remoteClose: Function ,
        categoryList:{
            type: Array, 
            default: []
        }
    },
    methods: {
        // 关闭窗口
        handleClose(){
            this.$refs.formData.resetFields()
            this.remoteClose()
        },
        // 提交表格，验证
        submitForm(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitData()
                } else {
                    this.$message({
                    message: '保存失败',
                    type: 'error'
                    });
                    return false;
                }
            });
        },
        // 提交数据，检验
        async submitData(){
            let response=null
            if(this.formData.id){
                response = await api.update(this.formData)

            }else{
                response = await api.add(this.formData)
            }
            
            if (response.code === 20000){
                this.$message({
                    message: '保存成功',
                    type: 'success'
                    });
                this.handleClose()
                
            }else{
                this.$message({
                    message: '保存失败',
                    type: 'error'
                    });
            }
        }

    },
    
}
</script>

<style>

</style>